#include <common.h>
#include <types.h>
#include <time.h>
#include <mysql.h>
#include <glib.h>

MYSQL *mysql;
MYSQL_RES *results;
MYSQL_ROW record;

static char *server_options[] = {
    "mysql_test",
    "--defaults-file=/tmp/mysql_test/my.cnf",
    "--datadir=/tmp/mysql_test/data",
    NULL
};

#define SERVER_OPTION_NUM ((sizeof(server_options) / sizeof(char *)) - 1)

static char *server_groups[] = {
    "embedded",
    "server",
    NULL
};

static const char hex_digits[] = "0123456789abcdef";
static void digest_to_string(char *digest, gsize digest_len, char *buf)
{
    int i;
    for (i = 0; i < digest_len; ++i) {
        uint8_t byte = digest[i];
        buf[i * 2] = hex_digits[byte >> 4];
        buf[i * 2 + 1] = hex_digits[byte & 0xf];
    }
    buf[digest_len * 2] = '\0';
}

int main(void)
{
    const char *home = g_get_home_dir();
    GString *default_file = g_string_new("--defaults-file=");
    g_string_append_printf(default_file, "%s/.syncup/my.cnf", home);
    GString *datadir = g_string_new("--datadir=");
    g_string_append_printf(datadir, "%s/.syncup/data", home);
    server_options[1] = default_file->str;
    server_options[2] = datadir->str;

    mysql_library_init(SERVER_OPTION_NUM, server_options, server_groups);
    mysql = mysql_init(NULL);
    mysql_options(mysql, MYSQL_READ_DEFAULT_GROUP, "embedded");
    mysql_options(mysql, MYSQL_OPT_USE_EMBEDDED_CONNECTION, NULL);

    if (!mysql_real_connect(mysql, NULL,NULL,NULL, NULL, 0, NULL,0)) {
        fprintf(stderr, "Failed to connect to database. Error: %s\n",
                mysql_error(mysql));
        goto err;
    }

    if (mysql_select_db(mysql, "syncuplocaldb")) {
        fprintf(stderr, "Failed to select database. Error: %s\n",
            mysql_error(mysql));
        goto err;
    }

    if (mysql_query(mysql, "SELECT * FROM syncup")) {
        fprintf(stderr, "Failed to query. Error: %s\n",
                mysql_error(mysql));
        goto err;
    }

    results = mysql_store_result(mysql);

    while((record = mysql_fetch_row(results))) {
        if (record[4] == NULL) {
            printf("%s - %s - %s - %s - %s\n",
                    record[0], record[1], record[2], record[3], record[4]);
        } else {
            char buf[41];
            digest_to_string(record[4], 20, buf);
            printf("%s - %s - %s - %s - x'%s'\n",
                    record[0], record[1], record[2], record[3], buf);
        }
    }

    mysql_free_result(results);
err:
    mysql_close(mysql);
    mysql_library_end();

    return 0;
}
